import axios from 'axios'
import errorCode from './errorCode.js'
import {VUE_APP_API_URL} from '@/config/index.js'
import {
	getToken
} from './auth/index.js';
/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	console.log("请求地址：" + req.url, req.data || req.params)
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	if (process.env.NODE_ENV === 'development') {
		console.log(`${res.config.url}响应结果：`, res)
	}
}


// 创建自定义接口服务实例
const request = axios.create({
	baseURL: VUE_APP_API_URL,
	timeout: 100000, // 不可超过 manifest.json 中配置 networkTimeout的超时时间
	// #ifdef H5
	withCredentials: true,
	// #endif
	headers: {
		'Content-Type': 'application/json',
		//'X-Requested-With': 'XMLHttpRequest',
	},
})

request.interceptors.request.use(config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	if (getToken() && !isToken) {
		config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
	}
	// get请求映射params参数
	if (config.method === 'get' && config.params) {
		let url = config.url + '?';
		for (const propName of Object.keys(config.params)) {
			const value = config.params[propName];
			var part = encodeURIComponent(propName) + "=";
			if (value !== null && typeof(value) !== "undefined") {
				if (typeof value === 'object') {
					for (const key of Object.keys(value)) {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						url += subPart + encodeURIComponent(value[key]) + "&";
					}
				} else {
					url += part + encodeURIComponent(value) + "&";
				}
			}
		}
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
	return config
}, error => {
	Promise.reject(error)
})

// 拦截器 在请求之后拦截
request.interceptors.response.use(res => {
		console.log('-----:'+res);
		// 未设置状态码则默认成功状态
		const code = res.data.code || 200;
		// 获取错误信息
		const msg = errorCode[code] || res.data.msg || errorCode['default']
		if (code === 500) {
			uni.showToast({
				title: msg,
				duration: 3000
			});
			return Promise.reject(new Error(msg))
		} else if (code !== 200) {
			uni.showToast({
				title: msg,
				duration: 1000
			});
			return Promise.reject('error')
		}
		return res;
	},
	error => {
		let {
			message
		} = error;
		if (message == "Network Error") {
			message = "后端接口连接异常";
		} else if (message.includes("timeout")) {
			message = "系统接口请求超时";
		} else if (message.includes("Request failed with status code")) {
			message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		uni.showToast({
			title: message,
			duration: 2000
		});
		return Promise.reject(error)
	}
)
export default request
